<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	ADMINKEYWORD class.
*
*	Administration of keywords
*****/
class ADMINKEYWORD
{
// Constructor
	function ADMINKEYWORD($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/SUCCESS.php");
		$this->success = new SUCCESS();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/html/TABLE.php");
		include_once("core/keyword/KEYWORD.php");
		$this->keyword = new KEYWORD($this->db);
		$this->keywords = $this->keyword->grabAll();
	}
// check we really are admin
	function gateKeep($method)
	{
		if(!$this->session->getVar("setup_superadmin"))
		{
			include_once("core/authorize/AUTHORIZE.php");
			$authorize = new AUTHORIZE($this->db);
			if($pString = $authorize->initLogon())
				return $pString;
		}
// else, run $method
		return $this->$method();
	}
// display options for categories
	function display($message = FALSE)
	{
		$this->template->setVar("heading", $this->messages->text("heading", "adminKeywords"));
		$pString = '';
		if($message)
			$pString .= MISC::p($message);
		if(is_array($this->keywords) && !empty($this->keywords))
		{
			$pString .= MISC::p($this->messages->text("misc", "keywordMerge"));
			$pString .= FORM::formHeader("mergeKeywords");
			$pString .= TABLE::tableStart();
			$pString .= TABLE::trStart();
			$pString .= TABLE::td(FORM::selectFBoxValueMultiple(FALSE, "keywordIds", $this->keywords, 20) . 
				MISC::br() . $this->messages->text("hint", "multiples"));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("misc", "keywordMergeTarget"), 
				"keywordText", FALSE, 50));
			$pString .= TABLE::trEnd();
			$pString .= TABLE::tableEnd();
//			$pString .= MISC::br() . "&nbsp;" . MISC::br();
			$pString .= MISC::p(FORM::formSubmit("Proceed"), FALSE, "right");
			$pString .= FORM::formEnd();
		}
		else
			$pString .= MISC::p($this->messages->text("misc", "noKeywords"));
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// start merging process
	function mergeProcess()
	{
		$this->validateInput();
		$this->keywordIds = $this->vars['keywordIds'];
		$newKeyword = trim($this->vars['keywordText']);
		$this->newKeywordId = $this->insertKeyword($newKeyword);
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
		foreach($this->keywordIds as $id)
		{
// Remove old keywords
			if($id != $this->newKeywordId)
				$this->db->delete("WKX_keyword", " WHERE " . $this->db->formatField('id') . '=' . 
				$this->db->tidyInput($id));
			$conditionArrayR[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
			$this->db->formatfield('keywords') . ", ','))";
			$conditionArrayQ[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
			$this->db->formatfield('quote_keywords') . ", ','))";
			$conditionArrayP[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
			$this->db->formatfield('paraphrase_keywords') . ", ','))";
			$conditionArrayM[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
			$this->db->formatfield('musing_keywords') . ", ','))";
		}
		$this->db->optimize("WKX_keyword");
// remove cache files for keywords
		$this->db->deleteCache('resourceKeywords');
		$this->db->deleteCache('metadataKeywords');
		$this->db->deleteCache('quoteKeywords');
		$this->db->deleteCache('paraphraseKeywords');
		$this->db->deleteCache('musingKeywords');
		$conditionR = " WHERE " . implode(" OR ", $conditionArrayR);
		$conditionQ = " WHERE " . implode(" OR ", $conditionArrayQ);
		$conditionP = " WHERE " . implode(" OR ", $conditionArrayP);
		$conditionM = " WHERE " . implode(" OR ", $conditionArrayM);
// Remove old keyword references from WKX_resource_keyword and add new keyword reference
		$resultSet = $this->db->select(array("WKX_resource_keyword"), array("id", "keywords"), $conditionR);
		$this->updateTable($resultSet, "WKX_resource_keyword", "keywords");
// Remove old keyword references from WKX_resource_quote and add new keyword reference
		$resultSet = $this->db->select(array("WKX_resource_quote"), 
			array("id", "quote_keywords"), $conditionQ);
		$this->updateTable($resultSet, "WKX_resource_quote", "quote_keywords");
// Remove old keyword references from WKX_resource_paraphrase and add new keyword reference
		$resultSet = $this->db->select(array("WKX_resource_paraphrase"), 
			array("id", "paraphrase_keywords"), $conditionP);
		$this->updateTable($resultSet, "WKX_resource_paraphrase", "paraphrase_keywords");
// Remove old keyword references from WKX_resource_musing and add new keyword reference
		$resultSet = $this->db->select(array("WKX_resource_musing"), 
			array("id", "musing_keywords"), $conditionM);
		$this->updateTable($resultSet, "WKX_resource_musing", "musing_keywords");
// Refresh the keyword list
		$this->keywords = $this->keyword->grabAll();
		return $this->display($this->success->text("keywordMerge"));
	}
// Update tables
	function updateTable($resultSet, $table, $field)
	{
		while($row = $this->db->fetchRow($resultSet))
		{
			$oldArray = explode(',', $row[$field]);
			$newArray = array_diff($oldArray, $this->keywordIds);
			$newArray[] = $this->newKeywordId;
			$ids = join(',', $newArray);
			$this->db->update($table, array($field => $ids), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['id']));
		}
		$this->db->optimize($table);
	}
// Insert new keyword or return ID if already exists
	function insertKeyword($keyword)
	{
		$this->keywordExists = TRUE;
		if($id = $this->keyword->checkExists($keyword))
			return $id;
		$this->keywordExists = FALSE;
		$fields[] = "keyword";
		$values[0] = $keyword;
// given keyword doesn't exist so now write to db
		$this->db->insert('WKX_keyword', $fields, $values);
		return $this->db->lastAutoId('WKX_keyword');
	}
// bad Input function
	function badInput($error, $method)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $this->$method($error));
	}
// validate input
	function validateInput()
	{
		if(!array_key_exists("keywordIds", $this->vars))
			$this->badInput($this->errors->text("inputError", "missing"), "display");
		if(!array_key_exists("keywordText", $this->vars) || !trim($this->vars['keywordText']))
			$this->badInput($this->errors->text("inputError", "missing"), "display");
	}
}
?>
